package com.zhazha.earlybird.dao;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.zhazha.earlybird.beans.DegreeInfo;

public class DegreeDAO {

	private SQLiteDatabase mDatabase;
	private static final String DEGREE_TABLE = "degree";
	
	private static final String DEGREE_ID 				= "id";
	private static final String DEGREE_NAME				= "name";
	
	private static final int DEGREE_ID_INDEX 			= 0;
	private static final int DEGREE_NAME_INDEX			= 1;
	
	DegreeDAO(SQLiteDatabase db) {
		mDatabase = db;
	}
	
	
	public boolean insert(DegreeInfo degree) {
		
		try {
			ContentValues cv = new ContentValues();
			cv.put(DEGREE_ID, 	degree.getId());
			cv.put(DEGREE_NAME,   degree.getName());
		
			this.mDatabase.insert(DEGREE_TABLE, null, cv);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
	}
	
	public boolean delete(int id) {
		try {
			String whereClause = "id=?";
			String[] whereArgs = {String.valueOf(id)};
			this.mDatabase.delete(DEGREE_TABLE, whereClause, whereArgs);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean update(int id, ContentValues cv) {
		try {
			String whereClause = "id=?";
			String[] whereArgs = {String.valueOf(id)};
			this.mDatabase.update(DEGREE_TABLE, cv, whereClause, whereArgs);
			return true;
		}catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public DegreeInfo queryById(int id) {
		DegreeInfo degree = null;
		
		try {
			String selection = "id=?";
			String[] selectionArgs = {String.valueOf(id)};
			Cursor c = this.mDatabase.query(DEGREE_TABLE, null, selection, selectionArgs, null, null, null);
			
			if(c.moveToFirst()) {
				degree = new DegreeInfo();
				degree.setId(c.getInt(DEGREE_ID_INDEX));
				degree.setName(c.getString(DEGREE_NAME_INDEX));
			}
			
			return degree;
			
		}catch (Exception e) {
			e.printStackTrace();
			return degree;
		}
	}
}
